#!/usr/bin/env python
from migrate_strategy import *
from tools import *
import os
import re
import platform
import subprocess
import sys
import time
import tempfile
import json

class Timer:
    def __init__(self, start=True):
        if start:
            self.start_time = time.time()
            self.acc = 0    # 累计的时间
        else:
            self.start_time = None
            self.acc = 0

    def pause(self):
        assert(self.start_time is not None)
        now = time.time()
        self.acc += now - self.start_time

    def resume(self):
        self.start_time = time.time()

    def elapsed(self):
        assert(self.start_time is not None)
        now = time.time()
        return now - self.start_time + self.acc
"""
用于运行判题器
"""

def run_strategy(input, output,parameter):
    o = open(output, 'w')
    i = open(input, 'r')
    result = Output(o)
    op_list, server_type_list, vm_type_dict = read_data_z_edition(i)
    solution = Strategy(op_list, vm_type_dict, server_type_list, parameter)
    solution.run(result)
    result.output()
    o.flush()
    o.close()
    i.close()


def calculate(executable, input, output) -> Tuple[int, int]:    # [成本,迁移次数]
    cmd = executable + ' %s %s' % (input, output)
    rc,out = subprocess.getstatusoutput(cmd)
    print(rc)
    print(out)
    lines = out.split('\n')
    cost = int(re.search(r'\d+', lines[0]).group())
    migration = int(re.search(r'\d+', lines[1]).group())
    return cost,migration


if __name__ == '__main__':
    parameter_best = parameter(9, 9, 76, 46, 9, 9, 76, 46, 0.06, 0.17)
    # 判题器的位置
    set_up_log(False)
    name = input('给本次运行起个名字，便于调参: ')
    if platform.system().startswith('L'):
        executable = '../../../judge'
    else:
        executable = r'..\..\..\judge.exe'
    input1 = '../../../data/training-1.txt'
    input2 = '../../../data/training-2.txt'
    if not os.path.exists(executable):
        l.fatal('no such file: %s' % (executable))
        sys.exit(-1)

    # 生成两个临时文件
    _,output1 = tempfile.mkstemp()
    _,output2 = tempfile.mkstemp()
    print('output1: %s' % (output1))
    print('output2: %s' % (output2))

    # 计时
    timer_a = Timer()
    print('Running on input1...')
    run_strategy(input1, output1,parameter_best)
    ta = timer_a.elapsed()

    timer_b = Timer()
    ServerInstance.instance_index = 0
    print('Running on input2...')
    run_strategy(input2, output2,parameter_best)
    tb = timer_b.elapsed()
    print('Time used: %.2fs=%.2f+%.2fs' % (ta+tb, ta, tb))

    cost1, migration1 = calculate(executable, input1, output1)
    cost2, migration2 = calculate(executable, input2, output2)

    print('Cost: %d=%d+%d' % (cost1+cost2, cost1, cost2))
    print('Migration: %d=%d+%d' % (migration1+migration2, migration1, migration2))
    print('Finished %s' % (name))

    # 算钱

    os.remove(output1)
    os.remove(output2)
